const express = require("express");
const app = express();
const session = require('express-session')

app.use(express.urlencoded());
app.use(express.json())

app.use(
    session({
        secret:'keyboard cat',
        resave:false,
        saveUninitialized:true
    })
)

app.post('/api/login',(req,res)=>{
    if(req.body.uname !='admin' ||req.body.pwd != '123456')
    return res.send({msg:'用户名或者密码错误'})

    req.session.user = req.body;
    req.session.isLogin = true;

    res.send({
        value: req.session.user,
        msg:'登录成功',
        session:req.session
    })
})

app.get('/api/home',(req,res)=>{
    console.log(req.session);
    if(!req.session.user) {
        return res.send({msg:'请先登录'})
    }
    res.send({name:'home',msg:'express-session',session:req.session.user})
})

app.post('/api/logout',(req,res)=>{
    req.session.destroy()
    res.send({name:'home',msg:'退出成功并清除session'})
})

app.listen(3000,()=>{
    console.log('3000 running')
})